<template>
	
	<form class="text-input">
		<!-- <view class="f-row"> -->
			<view style="width: 100%;display: flex;align-items: center;justify-content: space-between;padding-left: 10rpx;padding-right: 10rpx;box-sizing: border-box;">
				<template v-if="istoyy">
					<image src="../../../../../static/images/yuyin.png" style="height: 58rpx;" mode="heightFix" @click="changeshurumode"/>
					<input
						class="f news"
						type="text"
						v-model="inputMessage"
						cursor-spacing="65"
						confirm-type="send"
						@confirm="sendMessage"
						@input="bindMessage"
						@tap="focus"
						@focus="focus"
						@blur="blur"
						placeholder="输入新消息"
						placeholder-style="color:#CFCFCF; padding-left:5px;"
						style="width: calc( 100% - 300rpx );background-color: #F1F7F7;"
						 />
				</template>
				<template v-else>
					<image src="../../../../../static/images/jp@2x.png" style="height: 58rpx;" mode="heightFix" @click="changeshurumode"/>
					<view style="width: calc( 100% - 300rpx );height: 70rpx;line-height: 70rpx;text-align: center;background-color: #F1F7F7;" @click="toggleRecordModal">按住  说话</view>
				</template>
				<image src="../../../../../static/images/bq@2x.png" style="height: 58rpx;" mode="heightFix" @click="tobq"/>
				<view v-if="inputMessage&&inputMessage.length>0" style="width: 100rpx;height: 100%;height: 70rpx;line-height: 70rpx;text-align: center;background-color: #00BAAD;color: #fff;" @click="sendBtn">发送</view>	 
				<image v-else src="../../../../../static/images/gengd@2x.png" style="height: 58rpx;" mode="heightFix" @click="toShowother"/>
			</view>	 
			
	</form>
	
</template>

<script>
	let msgType = require("../../../msgtype");
	let disp = require("../../../../../utils/broadcast");
	const WxAuth =  require('@/utils/wxlogin');
	export default {
		components: {
			
		},
		props: {
			username: {
				type: Object,
				value: {},
			},
			chatType: {
				type: String,
				value: msgType.chatType.SINGLE_CHAT,
			},
			orderExt: {
				type: Object,
				value: {},
			},
		},
		data() {
			return {
				istoyy: true,
				inputMessage: "",		// render input 的值
				userMessage: "",		// input 的实时值
			}
		},
		created() {
			
		},
		
		onReady() {
			
		},
		methods: {
			changeshurumode(){
				this.istoyy = !this.istoyy
			},
			tobq(){
				this.$emit('tobq')
			},
			toggleRecordModal(){
				this.$emit('toyuyy')
			},
			toShowother(){
				this.$emit('toShowother')
			},
			sendBtn(){
				this.sendMessage()
				this.$emit('gbEmoji')
			},
			focus(){
				this.$emit('inputFocused')
			},
			
			blur(){
				this.$emit('inputBlured')
			},
			
			isGroupChat(){
				return this.chatType == msgType.chatType.CHAT_ROOM;
			},
			
			getSendToParam(){
				return this.isGroupChat() ? this.username.groupId : this.username.your;
			},
			
			// bindinput 不能打冒号！
			bindMessage(e){
				this.userMessage = e.detail.value
			},
			
			emojiAction(emoji){
				var str;
				var msglen = this.userMessage.length - 1;
				if(emoji && emoji != "[del]"){
					str = this.userMessage + emoji;
				}
				else if(emoji == "[del]"){
					let start = this.userMessage.lastIndexOf("[");
					let end = this.userMessage.lastIndexOf("]");
					let len = end - start;
					if(end != -1 && end == msglen && len >= 3 && len <= 4){
						str = this.userMessage.slice(0, start);
					}
					else{
						str = this.userMessage.slice(0, msglen);
					}
				}
				this.userMessage = str,
				this.inputMessage = str
			},
			
			//登录环信
			loginHX(userId){
				var test_account = userId+'';
				var test_psword = 123456;
				uni.setStorageSync("usrUserId",test_account)
				uni.setStorageSync("myUsername",test_account);
				this.$conn.open({
					apiUrl: this.$im.config.apiURL,
					user: test_account,
					pwd: test_psword,
					grant_type: "password",
					appKey: this.$im.config.appkey
				});
			},
			
			sendMessage(){
				let me = this;
			
				String.prototype.trim=function()
				{
				     return this.replace(/(^\s*)|(\s*$)/g, '');
				}
				if(!this.userMessage.trim()){
					return;
				}
				var orderExt = me.orderExt;
				let id = this.$im.conn.getUniqueId();
				let msg = new this.$im.message(msgType.TEXT, id);
				this.loginHX(orderExt.userId);
				msg.set({
					msg: this.userMessage,
					from: this.username.myName,
					ext: {'orderid':orderExt.orderId, 'messageType':orderExt.messageType, 'doctor_id':orderExt.doctorId, 'doctor_head':orderExt.doctorHead, 'doctor_nickname':orderExt.doctorNickname, 'user_id':orderExt.userId, 'user_head':orderExt.userHead, 'user_nickname':orderExt.userNickname},
					to: this.getSendToParam(),
					roomType: false,
					chatType: this.chatType,
					success(id, serverMsgId){
						console.log('成功了')
						disp.fire('em.chat.sendSuccess', id, me.userMessage);
						//往数据库存文本数据
						orderExt.receive = me.username.your;
						orderExt.send = me.username.myName;
						orderExt.content = me.userMessage;
						orderExt.type = 'txt';
						orderExt.chatId = serverMsgId;
						orderExt.audioLength = 0;
						var messages = JSON.stringify(orderExt);
						let usrUserId=uni.getStorageSync('usrUserId')
											let openid=uni.getStorageSync('openId')
											uni.request({
												url: 'https://app.mzmzb.com/application-usrapp/wx/saveTxtMessage.tz',
												data: {message:messages,type:'txt'},
												header : {'content-type':'application/x-www-form-urlencoded',
												'usruserid': usrUserId,
												'openid': openid,
												'hspid': 23840},
												method:"POST",
												success: (item) => {
													if(item.data.success){
														console.log("添加成功")
														uni.request({
															url: 'https://app.mzmzb.com/application-usrapp/login/hxStatusReport.tz?usrUserId=' +
																usrUserId + '&type=0&errMsg=' +me.userMessag,
															method: 'POST',
															header: {
																'usruserid': usrUserId,
																'openid': openid,
																'hspid': 23840
															},
															success: (res) => {
																console.log(res)
															}
														})
														// this.getCharList();
													}else{
														
													}
												}
											})
											
												this.calcUnReadSpot(message);
												// this.ack(message);
												
											this.func.$request('wx/sendChatMsgApplet.tz',{message:messages},'POST','application/x-www-form-urlencoded').then(item=>{
												console.log("添加成功")
											}).catch(error=>{
												console.log("失败")
											})
										},
										fail(id, serverMsgId){
											let usrUserId=uni.getStorageSync('usrUserId')
											let openid=uni.getStorageSync('openId')
											uni.request({
												url: 'https://app.mzmzb.com/application-usrapp/login/hxStatusReport.tz?usrUserId=' +
													usrUserId + '&type=1&errMsg=' + me.userMessage,
												method: 'POST',
												header: {
													'usruserid': usrUserId,
													'openid': openid,
													'hspid': 23840
												},
												success: (res) => {
													console.log(res,'日志')
												}
											})
											console.log('失败了')
										}
									});
									if(this.chatType == msgType.chatType.CHAT_ROOM){
										msg.setGroup("groupchat");
									}
									try{
										this.$im.conn.send(msg.body);
									}catch(e){
										console.log(e);
									}
									
									uni.$emit('saveSendMsg', {
										msg: msg,
										type: msgType.TEXT,
									})
									setTimeout(() => {
										this.userMessage = '';
										this.inputMessage = '';
									}, 300)
								},
							}
						}
</script>

<style>
	
.text-input {
	width: 100%;
	height: 100rpx;
	padding: 0;
	display: block;
}

.news {
	width: 100%;
	height: 62rpx;
	font-size: 14px;
	padding: 0 32rpx;
	display: inline-block;
	margin-top: 10rpx;
	line-height: 48rpx;
	position:relative;
	top: 0;
}

.send_btn {
	width: 80rpx;
	height: 60rpx;
	line-height: 60rpx;
	font-size: 17px;
	color: #000;
	padding: 0;
	display: inline-block;
	float: right;
	margin: 8rpx 16rpx auto auto;
	background-color: #fff;
}

.f-row{
	height:100rpx;
	display:flex;
	align-items:center;
}

</style>
